package com.aaa.forum.services.impl;

import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.dao.UserMapper;
import com.aaa.forum.exception.ApplicationException;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IUserService;
import com.aaa.forum.services.IUserSettingService;
import com.aaa.forum.uitls.MD5Util;
import com.aaa.forum.uitls.StringUtil;
import com.aaa.forum.uitls.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IUserSettingService userSettingService;

    @Override
    public void createNormalUser(User user) {
        // 1. 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            // 参数校验失败
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出 ApplicationException 异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 校验用户是否已存在
        User existsUser = userMapper.selectByUserName(user.getUsername());
        if (existsUser != null) {
            // 用户名已被占用（用户存在状态正常/用户处于被删除状态）
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = " + user.getUsername());
            // 抛出 ApplicationException 异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 设置用户默认值
        // 虽然数据库中设置了默认值, 但是最后我们提供默认值, 尽量不要让数据库去处理, 减轻数据库的负担
        user.setGender((byte) 2);       // 性别
        user.setArticleCount(0);        // 帖子数量
        user.setIsAdmin((byte) 0);      // 是否管理员
        user.setState((byte) 0);        // 状态
        user.setDeleteState((byte) 0);  // 是否被禁言
        // 日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 4. 写入数据库
        int row = userMapper.insertSelective(user); // 使用自动生成的 SQL
        if (row != 1) {
            // 插入失败
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString() + "username =" + user.getUsername());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 5. 初始化用户设置信息
        userSettingService.UserInit(user.getId());

        log.info("新增用户成功, username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        // 1. 非空校验
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 返回查询结果
        User user = userMapper.selectByUserName(username);
        if (user == null || user.getDeleteState() == 1) return null;
        else return user;
    }

    @Override
    public User login(String username, String password) {
        // 1. 非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 根据用户名查询用户信息
        User user = userMapper.selectByUserName(username);

        // 3. 校验查询结果是否为空
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", 用户不存在 username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 4. 校验密码是否正确
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!user.getPassword().equals(encryptPassword)) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误 username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        // 5. 校验通过, 登录成功, 返回用户信息
        log.info("登录成功, username = " + username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        // 1. 非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 查询并返回用户对象
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 查询对应的用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 3. 更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES + ", userId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2. 查询对应的用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 3. 更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断-1之后,是否小于0
        if (updateUser.getArticleCount() < 0) updateUser.setArticleCount(0);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES + ", userId = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null || existsUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        boolean checkAttr = false;
        User updateUser = new User();
        updateUser.setId(user.getId());

        // 校验用户名
        if (!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existsUser.getUsername())) {
            // 当 username 不为空 且 username 被修改的情况下
            // 校验新的 username, 是否未被使用
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                log.warn(ResultCode.FAILED_USERNAME_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USERNAME_EXISTS));
            }

            // 通过校验
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }

        // 校验昵称
        if (!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())) {
            // nickname 不为空, 且nickname被修改的情况下
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

        // 校验性别
        if (user.getGender() != null && !user.getGender().equals(existsUser.getGender())) {
            updateUser.setGender(user.getGender());
            // 校验合法性, 不合法的情况, 就设置为 2
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }

        // 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        // 校验电话号
        if (!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }

        // 校验个人简介
        if (!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }

        // 如果没有可以更新的字段,就抛出异常
        if (!checkAttr) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        updateUser.setUpdateTime(new Date());

        // 调用DAO,更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "更新数据库失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        User user = userMapper.selectByPrimaryKey(id);
        // 校验用户是否存在
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() );
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 校验旧密码是否正确
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() );
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 生成盐值
        String salt = UUIDUtil.UUID_32();
        // 计算新密码
        String newEncryptPassword = MD5Util.md5Salt(newPassword, salt);
        // 构造更新对象
        User modifyUser = new User();
        modifyUser.setId(user.getId());
        modifyUser.setPassword(newEncryptPassword);
        modifyUser.setSalt(salt);
        modifyUser.setUpdateTime(new Date());

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(modifyUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "更新数据库失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public List<User> selectByNickname(String nickname) {
        if (StringUtil.isEmpty(nickname)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByNickname(nickname);
    }

    @Override
    public void modifyAvatar(Long id, String avatarUrl) {
        // 非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(avatarUrl)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        // 校验用户是否存在
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() );
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 构造更新对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setAvatarUrl(avatarUrl);
        updateUser.setUpdateTime(new Date());
        // 调用dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyState(Long id, Byte state) {
        // 参数校验
        if (id == null || id <= 0 || (state != 0 && state != 1)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 构造更新对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setState(state);
        updateUser.setUpdateTime(new Date());
        // 调用dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<User> selectByState(Byte state) {
        return userMapper.selectByState(state);
    }
}
